/**
 * 
 */
package org.statewalker.validator.impl;

import org.statewalker.validator.IParseKey;

public class ParseKey implements IParseKey {

    private final IdGenerator fGenerator;

    private final int fId;

    private final String fName;

    private IParseKey fParent;

    public ParseKey(IdGenerator generator, String name) {
        fGenerator = generator;
        fId = fGenerator.newId();
        fName = name;
    }

    protected void checkIdGenerator(IParseKey key) {
        if (key != null
            && (!(key instanceof ParseKey) || fGenerator != ((ParseKey) key).fGenerator)) {
            throw new IllegalArgumentException();
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof ParseKey))
            return false;
        ParseKey o = (ParseKey) obj;
        return fId == o.fId && fGenerator == o.fGenerator;
    }

    /**
     * @see org.statewalker.validator.IParseKey#getName()
     */
    public String getName() {
        return fName;
    }

    /**
     * @see org.statewalker.validator.IParseKey#getParent()
     */
    public IParseKey getParent() {
        return fParent;
    }

    @Override
    public int hashCode() {
        return fId;
    }

    /**
     * @see org.statewalker.validator.IParseKey#setParent(org.statewalker.validator.impl.ParseKey)
     */
    public void setParent(IParseKey parent) {
        checkIdGenerator(parent);
        fParent = parent;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        if (fParent != null) {
            buf.append(fParent);
            buf.append("/");
        }
        buf.append(fName);
        return buf.toString();
    }

}